/*
 * Created on June 6, 2006
 * 
 * Copyright (c) Patrick Armstrong 2002-2007. All Rights Reserved
 */
package org.dime.mine.ui;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
import java.util.jar.JarFile;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;

import org.dime.mine.game.Board;

/**
 * Icons // TODO Add type summary
 *
 * @author Owner
 */
public class Icons
{
    public static int ZERO = 0; 
    public static int ONE = 1;
    public static int TWO = 2;
    public static int THREE = 3;
    public static int FOUR = 4;
    public static int FIVE = 5;
    public static int SIX = 6;
    public static int SEVEN = 7;
    public static int EIGHT = 8;
    public static int MARK = Board.MARKED;
    public static int MINE = Board.MINE;
    public static int NONE = Board.NOT_OPEN;
    public static int PRESSED = Integer.MAX_VALUE - 1;
    
    private static final String jarPath = "./Mine.jar";
    private static final String iconsPath = "icons/";
    private static final String iconsExt = ".png";
    
    private static final Map<Integer, ImageIcon> icons = new HashMap<Integer, ImageIcon>();
    
    private static JarFile jar;

    public static void initialize()
    {
        Field[] fields = Icons.class.getDeclaredFields();
        Integer key;
        for (int i = 0; i < fields.length; i++)
        {
            if(fields[i].getType().equals(int.class))
            {
                try
                {
                    String filename = fields[i].getName().toLowerCase();
                    filename = iconsPath + filename + iconsExt;
                    
                    key = new Integer(fields[i].getInt(null));
                    icons.put(key, getImageIcon(filename));
                }
                catch (IllegalAccessException iae)
                {}
                catch (IOException ioe)
                {
                    throw new RuntimeException(
                            "Could not open an image file", ioe);
                }
            }
        }
    }

    public static ImageIcon getIcon(int code)
    {
        return icons.get(new Integer(code));
    }

    private static ImageIcon getImageIcon(String filename) throws IOException
    {
        InputStream input = null;
        try
        {
            input = new FileInputStream(filename);
        }
        catch (FileNotFoundException fnfe)
        {
            if (jar == null)
                jar = new JarFile(jarPath);

            input = jar.getInputStream(jar.getEntry(filename));
        }

        return new ImageIcon(ImageIO.read(input));
    }
}
